package com.wxy.school.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.school.common.R;
import com.wxy.school.dto.SignUpDto;
import com.wxy.school.entity.Job;
import com.wxy.school.entity.SignUp;
import com.wxy.school.service.JobService;
import com.wxy.school.service.SignUpService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王祥宇
 * @projectName school
 * @packageName com.wxy.school.controller
 * @data 2023/4/18 11:23
 * @description: TODO
 * @version: 1.0
 */
@RestController
@RequestMapping("school/signUp")
public class SignUpController {

    @Resource
    private SignUpService signUpService;

    @Resource
    private JobService jobService;

    @PostMapping("/addSignUp")
    public R<String> add(@RequestBody SignUp signUp){
        signUp.setSignUpTime(LocalDateTime.now());
        Job job = jobService.getById(signUp.getJobId());
        job.setQuota(job.getQuota() - 1);
        jobService.updateById(job);
        signUpService.save(signUp);
        return R.success("报名申请已提交");
    }

    @GetMapping("/getSignUp/{id}")
    public R<List<SignUpDto>> get(@PathVariable Long id){
        LambdaQueryWrapper<SignUp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SignUp::getUserId, id);
        lambdaQueryWrapper.orderByDesc(SignUp::getSignUpTime);
        List<SignUp> signUpList = signUpService.list(lambdaQueryWrapper);
        List<SignUpDto> signUpDtoList = signUpList.stream().map((item) -> {
            SignUpDto signUpDto = new SignUpDto();
            BeanUtils.copyProperties(item, signUpDto);
            LambdaQueryWrapper<Job> jobLambdaQueryWrapper = new LambdaQueryWrapper<>();
            jobLambdaQueryWrapper.eq(Job::getId, item.getJobId());
            signUpDto.setJob(jobService.getOne(jobLambdaQueryWrapper));
            return signUpDto;
        }).collect(Collectors.toList());
        return R.success(signUpDtoList);
    }

    @DeleteMapping("/deleteSignUp/{signUpId}")
    public R<String> delete(@PathVariable Long signUpId){
        SignUp signUp = signUpService.getById(signUpId);
        Job job = jobService.getById(signUp.getJobId());
        job.setQuota(job.getQuota() + 1);
        jobService.updateById(job);
        signUpService.removeById(signUpId);
        return R.success("报名申请撤销成功");
    }

    @GetMapping("/getSignUpList")
    public R<Page> getSignUp(int pageNum, int pageSize, String qurey, Long jobId){
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<SignUp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SignUp::getJobId, jobId);
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(qurey), SignUp::getSignUpName, qurey);
        lambdaQueryWrapper.orderByDesc(SignUp::getSignUpTime);
        signUpService.page(page, lambdaQueryWrapper);
        return R.success(page);
    }

    @GetMapping("/getSignUpOne/{id}")
    public R<SignUp> getOne(@PathVariable Long id){
        SignUp signUp = signUpService.getById(id);
        return R.success(signUp);
    }

    @PutMapping("/updateSignUp")
    public R<String> update(@RequestBody SignUp signUp){
        signUpService.updateById(signUp);
        return R.success("保存成功");
    }

    @PostMapping("/exportExcel/{jobId}")
    public void exportExcel(@PathVariable Long jobId, HttpServletResponse response) throws IOException{
        LambdaQueryWrapper<SignUp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SignUp::getJobId, jobId);
        List<SignUp> signUpList = signUpService.list(lambdaQueryWrapper);
        List<SignUpDto> signUpDtoList = signUpList.stream().map((item) -> {
            SignUpDto signUpDto = new SignUpDto();
            BeanUtils.copyProperties(item, signUpDto);
            return signUpDto;
        }).collect(Collectors.toList());
        for (SignUpDto signUpDto : signUpDtoList) {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            signUpDto.setTime(df.format(signUpDto.getSignUpTime()));
            if (signUpDto.getSignUpSex() == 0) {
                signUpDto.setSex("男");
            } else {
                signUpDto.setSex("女");
            }
        }
        Job job = jobService.getById(jobId);
        String fileName = new String(job.getJobName().getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName );
        EasyExcel.write(response.getOutputStream(), SignUpDto.class).sheet(job.getJobName()).doWrite(signUpDtoList);
    }
}
